package com.ywyt.simple;

import com.rabbitmq.client.*;
import com.ywyt.util.ConnUtil;
import org.junit.Test;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class SimpleConsumer {
    @Test
    public void Receive() throws IOException, TimeoutException {
        //获取连接
        Connection connection = ConnUtil.getConnection();
        //获取channel
        Channel channel = connection.createChannel();
        //声明队列
        channel.queueDeclare(SimpleProvider.QUEUE_NAME,false,false,false,null);
        //消费队列
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //接收消息
                String msg = new String(body, "UTF-8");
                System.out.println("接收到的消息"+msg);
            }
        };
        //消费消息
        channel.basicConsume(SimpleProvider.QUEUE_NAME,true,defaultConsumer);
        //System.in.read();
        channel.close();
        connection.close();
    }
}
